<?php
class ToolController extends App_Zend_Controller_Action_Shop
{
	public function indexAction()
	{
		$this->getHelper('layout')->disableLayout();
    	$this->getHelper('viewRenderer')->setNoRender();
    	
    	$src = $this->getRequest()->getParam('src', '');
    	$left = $this->getRequest()->getParam('left', 100);
    	$top  = $this->getRequest()->getParam('top', 100);
    	$width = $this->getRequest()->getParam('width', 50);
    	$height = $this->getRequest()->getParam('height', 50);
    	
    	$content = file_get_contents($src);
    	$path = MY_ROOT . '/cache/' . time() . '.jpg';
    	file_put_contents($path, $content);
    	
    	$thumbPath = MY_ROOT . '/water.png';
    	
    	$image = new Gmagick($path);
    	$image2 = new Gmagick($thumbPath);
    	$image2->thumbnailImage($width, $height);
    	$image->compositeImage($image2, Gmagick::COMPOSITE_OVER, $left, $top);
    	
    	header("Content-Type: image/jpg"); 
		$seconds_to_cache = 3600 * 24 * 360;
		$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
		header("Expires: $ts");
		header("Pragma: cache");
		header("Cache-Control: max-age=$seconds_to_cache");
		@unlink($path);
		echo $image; 
	}
	public function statuAction(){
		$email = $this->getRequest()->getParam('rewardemail');
		$ordernumber = $this->getRequest()->getParam('ordernumber');
		if(empty($email) || empty($ordernumber)){
			echo "statu=4";
			exit();
		}
		$member = new CMember();
		if(empty($_COOKIE['zcshop_uid'])){
			echo "statu=2";
		}else{
			$where = array('email'=>$email);
			$userinfo = $member->getUserDetails($where);
			if(!empty($userinfo)){
				$orderModel = new COrder();
				$orderinfo = $orderModel->getOrderByUid($userinfo[0]['uid']);
				$orderid =array();
				if(!empty($orderinfo)){
					foreach($orderinfo as $v){
						$orderid[]=$v['orderid'];
					}
					//查看订单号是否正确
					if(in_array($ordernumber, $orderid)){
						$rewardModel = new CReward();
						$where = array('uid = ?'=>$userinfo[0]['uid'],'orderid = ?'=>$ordernumber);
						$res = $rewardModel->fetchRow($where);
						if(empty($res)){
							$data['uid'] = $userinfo[0]['uid'];
							$data['orderid'] = $ordernumber;
							$rewardModel->insert($data);
							echo "statu=1";//没抽过奖
						}else{
							echo "statu=3";//已抽奖
						}
					}else{
						echo "statu=4";
					}
				}else{
					echo "statu=4";
				}
			}
		}
		//先检查是否登录，未登录返回2
		//从表zcshop_order_reward中查询是否有数据，如果没有或者is_reward=1就返回3
		//否则返回1
		exit();
	}
	public function turnplateAction(){
		header('Content-Type:text/html;charset=utf-8');
		$arrTurn = array(180,5,355,45,225,45,225,45,225,45,225,180,45,315,45,355,5,225,225,45);
		
		
		$couponcode = new CCouponCode();
		$code='';
		while(empty($code)){
			$KEYWORD = 'abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ0123456789';
			$postr = str_shuffle($KEYWORD);
			$pos = mt_rand(0,strlen($postr) - 20);
			$code = '';
			while (empty($code))
			{
				$code = substr($postr,$pos,mt_rand(15,20));
				if ($couponcode->isexist($code))
				{
					$code = '';
				}
			}
		}
		
		
		
		$socre='';
		
		if ( $_POST['act'] == 'turnPlate') {
			$key = rand(0,19);
			if($arrTurn[$key]==315){
				$tips ='Congratulations!You win a $20 coupon,your coupon code has been sent to your email';
				$score=10000;
			}elseif ($arrTurn[$key]==180){
				$tips ='Congratulations!You win a $10 coupon,your coupon code has been sent to your email';
				$score=5000;
			}elseif($arrTurn[$key]==5 || $arrTurn[$key]==355){
				$tips ='Congratulations!You win a $5 coupon,,your coupon code has been sent to your email';
				$score=2500;
			}else{
				$tips =' Thanks for your participation.';
			}
			if(!empty($score)){
				$itemarray = array(
						'code'		=>	$code,
						'from'		=>	'exclusive sale',
						'score'		=>  $score,
						'createtime'=>	time(),
						'endtime'	=>  time()+24*3600*30
				);
				$couponcode->createcode($itemarray);
				$email = $this->getRequest()->getParam('rewardemail');
				$config = array('auth' => 'login',
						'username' => 'service@fancycheapjersey.com',
						'password' => 'qa1234'
				);
				$transport = new Zend_Mail_Transport_Smtp('smtp.exmail.qq.com',$config);
				$mail = new Zend_Mail();
				$mail->addTo($email,$email);
				$mail->setFrom('service@fancycheapjersey.com', 'service@fancycheapjersey.com');
				$mail->setSubject('Congratulations!You win a coupon');
				$mail->setBodyText('Congratulations!You win a '.$score.'coupon,your coupon is '.$code);
				$res = $mail->send($transport);
			}
			$hudu = 720+$arrTurn[$key];   //随机选一种弧度，弧度你可以自己控制，前面720表是在原来基础上多加两圈
			echo '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="497" height="497" id="turnplate">
			<param name="allowScriptAccess" value="always" />
			<param name="FlashVars" id="FlashVars" value="fvar='.$hudu.'&tips='.$tips.'">
			<param name="movie" value="http://www.fancycheapjersey.com/html/flash/turnplate.swf">
			<param name="menu" value="false">
			<param name="quality" value="high">
			<param name="wmode" value="transparent">
			<embed src="http://www.fancycheapjersey.com/html/flash/turnplate.swf" FlashVars="fvar='.$hudu.'&tips='.$tips.'" id="FlashVars"  width="497" height="497"  quality="high" id="turnplate" name="turnplate" wmode="transparent" allowScriptAccess="always"  pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash">
			</embed>
			</object>';
			exit();
		}
	}
	
	public function translateAction(){
		
		$this->getHelper('layout')->disableLayout();
    	$this->getHelper('viewRenderer')->setNoRender();
				//demo 1
		$Google = new GoogleTranslate();
		$Google->text = '这是一个基于Google在线翻译的工具';
		$Google->from = 'zh-CN';
		$Google->to = 'fr';
		$Google->translate();
		echo '<pre>';
		print_r($Google->json);
		echo '</pre>';
		//demo 2
		$Google = new GoogleTranslate('这是一个基于Google在线翻译的工具', 'zh-CN', 'en');
		echo $Google->result;
		
		//demo 3
		$Google = new GoogleTranslate();
		$Google->translate('这是一个基于Google在线翻译的工具', 'zh-CN', 'en');
		echo $Google->result;
	}
	
	public function sendexpireAction()
	{		
		$this->getHelper('layout')->disableLayout();
    	$this->getHelper('viewRenderer')->setNoRender();
    	
    	$pass = $this->getRequest()->getParam('p', '');
    	if ($pass != 'fancycheapjersey') {
    		return;
    	}
    	
		$cart = new CCart();
		
		$cartList = $cart->fetchAll(array('uid > ?'=>0, 'expires > ?'=>time()+15379200, 'expires < ?'=>time()+15465600));
		
		$uid = array();
		$uidHasCouponCode = array();
		$order = new COrder();
		$orders = $order->fetchAll(array('flid <> ?'=>1, 'add_time < ?'=>time()-86400, 'add_time > ?'=>time()-172800));	
		$orders2 = $order->fetchAll(array('coupon > ?'=>0, 'flid = ?'=>1,'add_time < ?'=>time()-86400, 'add_time > ?'=>time()-172800));	
				
		foreach ($orders as $v) {
			$uid[] = $v->uid;
		}
		
		$result = array();
		foreach ($cartList as $v) {
			if (!in_array($v->uid, $uid)) {
				$result[] = $v->uid;
			}
		}
		
		foreach ($orders2 as $v) {
			$uidHasCouponCode[] = $v->uid;
		}
		
		$config=new CConfigpayemail();
        $array=$config->getAllConfigpayemail();
        $configArray=array();
        foreach ($array as $value) {
            $configArray[$value['name']]=$value['data'];
        }
        
        $member = new CMember();
        $itemModel = new CItem();
        foreach ($result as $v) {
	        $itemStr = '';
        	$memberArr = $member->getUserDetails(array('uid'=>$v));        	
	        $to = $memberArr[0]['username'];
        	$cartStr = $cart->getCartStrByUid($v);
        	if ($cartStr) {
	           	$shoppingArray=json_decode(stripslashes($cartStr),true);
			}
			
			if (empty($shoppingArray)) {
				continue;
			}
			
			//item
			$tmp = array();
			foreach ($shoppingArray as $k=>$v) {
				$str = $itemModel->find($k)->current();
				$tmp[] = $str->subject;
			}
			$itemStr = implode('<br>', $tmp);
			$code = '';
			if (false) {				
				//coupon code
				$couponcode = new CCouponCode();
				$KEYWORD = 'abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ0123456789';
				$postr = str_shuffle($KEYWORD);
				$pos = mt_rand(0,strlen($postr) - 20);
				$code = '';
				while (empty($code))
		        {
		            $code = substr($postr,$pos,mt_rand(15,20));
		            if ($couponcode->isexist($code))
		            {
		                $code = '';
		            }
		        }	    	
				$itemarray = array(
					'code'		=>	$code,
					'from'		=>	'email',
					'score'		=>  '1500',
					'createtime'=>	time(),
					'endtime'	=>  time()+3600*24*4
				);
				$couponcode->createcode($itemarray);
				//
				
				$message = 'We noticed that you did not complete your order during your last visit to our site. <br>
				Just in case you were interrupted, we have saved your cart for you : http://www.fancycheapjersey.com/product-showitem . <br>
				Additionally, we provide you a coupon code: {coupon} for this cart. Just sign in with {email}, then check your cart, and apply the code.<br>
				The items of your cart:<br>
				{item_str}<br>
				If you had trouble checking out or found something confusing, please contact our customer service department by email at service@fancycheapjersey.com .
				Also, remember you can use "My Wish List" (http://www.fancycheapjersey.com/adminb?iframeUrl=adminb-favor-items) to save your favorite products in one place. They\'ll be easy to find when you want to make a future purchase. To save a product, just click on "add to my wish list" on any product page.
				Thank you for visiting fancycheapjersey.com!<br>
				fancycheapjersey.com<br>';
			}else{
				$message = 'We noticed that you did not complete your order during your last visit to our site. <br>
				Just in case you were interrupted, we have saved your cart for you : http://www.fancycheapjersey.com/product-showitem . <br>
				Just sign in with {email}, then check your cart.<br>
				The items of your cart:<br>
				{item_str}<br>
				If you had trouble checking out or found something confusing, please contact our customer service department by email at service@fancycheapjersey.com .
				Also, remember you can use "My Wish List" (http://www.fancycheapjersey.com/adminb?iframeUrl=adminb-favor-items) to save your favorite products in one place. They\'ll be easy to find when you want to make a future purchase. To save a product, just click on "add to my wish list" on any product page.
				Thank you for visiting fancycheapjersey.com!<br>
				fancycheapjersey.com<br>';
			}
			
	        $subject = 'Your Shopping Cart is still waiting for you at fancycheapjersey';
	        $messageSend = str_replace("{item_str}",$itemStr, $message);	
	        $messageSend = str_replace("{email}",$to, $messageSend);
	        $messageSend = str_replace("{coupon}",$code, $messageSend);
	
	        $messageSend = str_replace("\r\n","<br>",$messageSend);
	        $from = $configArray['EMAIL_BOX'];
	        $mail = new CMail();
	        $mail->sendEmail('service@fancycheapjersey.com', $to, $subject, $messageSend);
        }
	}
}


